﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace Staticage.Core {
    public class ThreadSafeExecutor<T> {

        Hashtable cache;

        public ThreadSafeExecutor(IDictionary<string, T> objects) {
            Preconditions.CheckNotNull(objects);
            Preconditions.CheckArgument(objects.Count > 0);

            this.cache = Hashtable.Synchronized(new Hashtable());

            foreach (string key in objects.Keys)
                cache.Add(Preconditions.CheckNotNull(key), Preconditions.CheckNotNull(objects[key]));
        }

        public TResult Excute<TResult>(string key, Func<T, TResult> func) {
            lock (this) {
                return func(Get(key));
            }
        }

        public ThreadSafeExecutor<T> Excute<TResult>(string key, Action<T> action) {
            lock (this) {
                action(Get(key));
            }
            return this;
        }

        private T Get(string key) {
            return (T)cache[key];
        }
    }
}
